<template>
	<div class="card-fill layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<el-form ref="formRef" :model="state.vmModel" label-width="120px">
				<el-row>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_GroupCode_FormItem" prop="Entity.GroupCode" :label="$t('message._admin.group.vm.GroupCode')">
							<el-input
								v-model="state.vmModel.Entity.GroupCode"
								clearable
								:disabled="state.vmModel.Entity.ParentId && !siteConfig.isCustomGroupCode"
								:placeholder="!state.vmModel.Entity.ParentId || siteConfig.isCustomGroupCode ? '请输入部门编码' : '自动生成'"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_GroupName_FormItem"
							prop="Entity.GroupName"
							:label="$t('message._admin.group.vm.GroupName')"
							:rules="[
								{
									required: true,
									message: $t('message._system.common.vm.input', { input: $t('message._admin.group.vm.GroupName') }),
									trigger: 'blur',
								},
							]"
						>
							<el-input v-model="state.vmModel.Entity.GroupName" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_ParentId_FormItem" prop="Entity.ParentId" :label="$t('message._admin.group.vm.ParentId')">
							<el-cascader
								:options="state.allGroups"
								:props="{ checkStrictly: true, emitPath: false, label: 'Text', value: 'Value', children: 'Children' }"
								clearable
								filterable
								class="w100"
								v-model="state.vmModel.Entity.ParentId"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_FullName_FormItem" prop="Entity.FullName" :label="$t('message._admin.group.vm.FullName')">
							<el-input v-model="state.vmModel.Entity.FullName" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_IsCompany_FormItem" prop="Entity.IsCompany" :label="$t('message._admin.group.vm.IsCompany')">
							<el-switch v-model="state.vmModel.Entity.IsCompany" clearable></el-switch>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_IsDisabled_FormItem" prop="Entity.IsDisabled" :label="$t('message._admin.group.vm.IsDisabled')">
							<el-switch v-model="state.vmModel.Entity.IsDisabled" clearable></el-switch>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_IsVirtual_FormItem" prop="Entity.IsVirtual" :label="$t('message._admin.group.vm.IsVirtual')">
							<el-switch v-model="state.vmModel.Entity.IsVirtual" clearable></el-switch>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_IsInheritParent_FormItem" prop="Entity.IsInheritParent">
							<template #label>
								<WtmLabelTooltip label="是否继承父级" tooltip="是否继承父级查询限制" />
							</template>
							<el-switch v-model="state.vmModel.Entity.IsInheritParent" clearable></el-switch>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_Order_FormItem" prop="Entity.Order" label="排序">
							<el-input-number v-model="state.vmModel.Entity.Order" :step="0.01"></el-input-number>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="ManagerJobPositionName_FormItem" prop="ManagerJobPositionName" label="管理者岗位名称">
							<el-input v-model="state.vmModel.ManagerJobPositionName" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="EmployeeJobPositionName_FormItem" prop="EmployeeJobPositionName" label="职员岗位名称">
							<el-input v-model="state.vmModel.EmployeeJobPositionName" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<el-col :xs="24" :lg="24" class="mb20">
						<el-form-item ref="Entity_GroupRemark_FormItem" prop="Entity.GroupRemark" :label="$t('message._admin.group.vm.GroupRemark')">
							<el-input v-model="state.vmModel.Entity.GroupRemark" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="24" class="mb20">
						<el-form-item label="组织">
							<!-- 穿梭框区域 -->
							<el-transfer
								v-model="state.selectedOrganizations"
								:titles="['可选组织', '已选组织']"
								:data="state.organizationList"
								:props="{ key: 'Value', label: 'Text' }"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import { ElMessage } from 'element-plus';
import { reactive, ref, getCurrentInstance, onMounted, watch, nextTick } from 'vue';
import frameworkgroupApi from '/@/api/frameworkgroup';
import other from '/@/utils/other';
import { useSiteConfig } from '/@/stores/siteConfig';
import { commonApi } from '/@/api/common';

const ci = getCurrentInstance() as any;
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);
// 站点配置
const siteConfig = useSiteConfig();
// 定义变量内容
const formRef = ref();
const state = reactive({
	vmModel: {
		Entity: {
			GroupCode: null,
			GroupName: null,
			ParentId: null,
			Manager: null,
			GroupRemark: null,
			IsCompany: false,
			IsDisabled: false,
			FullName: null,
			IsVirtual: false,
			IsInheritParent: true, // 默认继承父级查询限制
			Level: 0,
			Order: 0,
		},
		ManagerJobPositionName: null as string | null,
		EmployeeJobPositionName: null as string | null,
		SelectedOrganizationIds: [] as string[],
	},
	allGroups: [] as any[],
	organizationList: [] as any[], // 穿梭框数据
	selectedOrganizations: [] as string[], // 已选组织ID列表
});

// 加载组织数据的公共方法
const loadOrganizations = async (parentId: string | number | null) => {
	let res;
	if (parentId && state.vmModel.Entity.IsInheritParent) {
		// 有父级且开启继承父级查询限制，带groupId参数
		res = await commonApi().getOrganizations(String(parentId));
	} else {
		// 无父级或不继承父级查询限制，不带参数
		res = await commonApi().getOrganizations();
	}
	state.organizationList = Array.isArray(res) ? res : [];
	state.selectedOrganizations = [];
	state.vmModel.SelectedOrganizationIds = [];
};

// 监听GroupName变化，联动更新岗位名称
watch(
	() => state.vmModel.Entity.GroupName,
	(newGroupName) => {
		if (newGroupName) {
			state.vmModel.ManagerJobPositionName = `${newGroupName}部门主管`;
			state.vmModel.EmployeeJobPositionName = `${newGroupName}职员`;
		} else {
			state.vmModel.ManagerJobPositionName = null;
			state.vmModel.EmployeeJobPositionName = null;
		}
	}
);

// 监听父级部门变化，自动获取组织信息
watch(
	() => state.vmModel.Entity.ParentId,
	async (newParentId) => {
		await loadOrganizations(newParentId);
	},
	{ immediate: true }
);

// 监听继承父级查询限制开关变化
watch(
	() => state.vmModel.Entity.IsInheritParent,
	async (newValue) => {
		await loadOrganizations(state.vmModel.Entity.ParentId);
	}
);

// 打开弹窗
onMounted(() => {
	other.getSelectList('/api/common/GetGroups?auth=false', [], false).then((x) => {
		state.allGroups = x;
	});
	nextTick(() => {
		setupHeaderButtons();
	});
});
// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			// 同步已选组织ID到vmModel
			state.vmModel.SelectedOrganizationIds = [...state.selectedOrganizations];
			frameworkgroupApi()
				.add(state.vmModel)
				.then(() => {
					ElMessage.success(ci.proxy.$t('message._system.common.vm.submittip'));
					emit('refresh');
					closeDialog();
				})
				.catch((error) => {
					other.setFormError(ci, error);
				});
		}
	});
};

// 暴露变量
defineExpose({});
// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: ci.proxy.$t('message._system.common.vm.submit'),
			type: 'primary',
			onClick: onSubmit,
			visible: true,
		},
		{
			text: ci.proxy.$t('message._system.common.vm.cancel'),
			type: 'default',
			onClick: onCancel,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
